package com.itheima.reggie.controller;


import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.itheima.reggie.common.R;
import com.itheima.reggie.dto.DishDto;
import com.itheima.reggie.entity.Category;
import com.itheima.reggie.entity.Dish;
import com.itheima.reggie.entity.DishFlavor;
import com.itheima.reggie.entity.SetmealDish;
import com.itheima.reggie.service.CategoryService;
import com.itheima.reggie.service.DishFlavorService;
import com.itheima.reggie.service.DishService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.web.bind.annotation.*;

import java.util.ArrayList;
import java.util.List;
import java.util.Set;
import java.util.concurrent.TimeUnit;
import java.util.stream.Collectors;

/**
 * 菜品管理
 */
@RestController
@RequestMapping("/dish")
@Slf4j
public class DishController {

    @Autowired
    private DishService dishService;

    @Autowired
    private DishFlavorService dishFlavorService;

    @Autowired
    private CategoryService categoryService;

    @Autowired
    private RedisTemplate redisTemplate;

    /**
     * 菜品添加
     * @param dto
     * @return
     */
    @PostMapping
    public R<String> save(@RequestBody DishDto dto) {
        log.info("save dish {}", dto);
        dishService.saveDishAndFlavor(dto);
        //清理redis特定菜品缓存
        String key = "dish_"+dto.getCategoryId()+"_1";
        redisTemplate.delete(key);
        //所有菜品缓存清除
//        Set keys = redisTemplate.keys("dish_*");
//        redisTemplate.delete(keys);
        return R.success("保存菜品成功");
    }

    /**
     * 分页管理
     * @param page
     * @param pageSize
     * @param name
     * @return
     */
    @GetMapping("/page")
    public R<Page> page(int page,int pageSize,String name){

        //分页构造器
        Page<Dish> pageInfo = new Page<>(page,pageSize);
        Page<DishDto> dishDtoPage = new Page<>();

        //条件构造器
        LambdaQueryWrapper<Dish> queryWrapper = new LambdaQueryWrapper<>();
        //过滤条件
//        name!= null 关注的是变量本身是否存在有效引用，而 name.isEmpty() 关注的是变量所引用的字符串内容是否为空。
        queryWrapper.like(name!=null ,Dish::getName,name);
        //排序条件
        queryWrapper.orderByDesc(Dish::getUpdateTime);

        //查询
        dishService.page(pageInfo,queryWrapper);
        //对象拷贝
        BeanUtils.copyProperties(pageInfo,dishDtoPage,"records");
        List<Dish> recordsDish = pageInfo.getRecords();

        List<DishDto> recordsDtoDish = recordsDish.stream().map((item)->{
            DishDto dto = new DishDto();
            BeanUtils.copyProperties(item,dto);
            Long categoryId = dto.getCategoryId();//分类id
            Category category = categoryService.getById(categoryId);
            if(category!=null){
                dto.setCategoryName(category.getName());
            }else{
                dto.setCategoryName("无");
            }
            return dto;
        }).collect(Collectors.toList());

        dishDtoPage.setRecords(recordsDtoDish);

        return R.success(dishDtoPage);
    }

    /**
     * 根据id查询菜品信息和对应的口味信息
     * @param id
     * @return
     */
    @GetMapping("/{id}")
    public R<DishDto> backDishDto(@PathVariable Long id){
        DishDto dishDto = dishService.getDishAndFlavor(id);
        return R.success(dishDto);
    }


    /**
     * 修改菜品信息和对应的口味信息
     * @param dishDto
     * @return
     */
    @PutMapping()
    public R<String> updateDishDto(@RequestBody DishDto dishDto){
        log.info("update dish {}", dishDto);
        dishService.updateDishAndFlavor(dishDto);
        //清理redis特定菜品缓存
        String key = "dish_"+dishDto.getCategoryId()+"_1";
        redisTemplate.delete(key);
        //所有菜品缓存清除
//        Set keys = redisTemplate.keys("dish_*");
//        redisTemplate.delete(keys);
        return R.success("修改菜品成功");
    }

    /**
     * 根据条件查询对应的菜品信息
     * @param dish
     * @return
     */
//    @GetMapping("/list")
//    public R<List<Dish>> getCategoryList(Dish dish){
//        //构造数据库
//        LambdaQueryWrapper<Dish> queryWrapper = new LambdaQueryWrapper<>();
//        //查询条件
//        queryWrapper.eq(dish.getCategoryId()!=null,Dish::getCategoryId,dish.getCategoryId());
//        queryWrapper.eq(Dish::getStatus,1);
//        //排序条件
//        queryWrapper.orderByAsc(Dish::getSort).orderByDesc(Dish::getUpdateTime);
//        List<Dish> dishs = dishService.list(queryWrapper);
//
//        return R.success(dishs);
//    }
    @GetMapping("/list")
    public R<List<DishDto>> getCategoryList(Dish dish){
        List<DishDto> dishDtoList = null;
        //根据传输创造key
        String key = "dish"+"_"+dish.getCategoryId()+"_"+dish.getStatus();

        dishDtoList = (List<DishDto>) redisTemplate.opsForValue().get(key);

        //判断之前是否已经存在，存在则返回redis缓存
        if(dishDtoList!=null){
            return R.success(dishDtoList);
        }

        //不存在，数据库查询
        //构造查询条件
        LambdaQueryWrapper<Dish> queryWrapper = new LambdaQueryWrapper<>();
        //查询条件
        queryWrapper.eq(dish.getCategoryId()!=null,Dish::getCategoryId,dish.getCategoryId());
        queryWrapper.eq(Dish::getStatus,1);
        //排序条件
        queryWrapper.orderByAsc(Dish::getSort).orderByDesc(Dish::getUpdateTime);

        List<Dish> dishList = dishService.list(queryWrapper);

        dishDtoList = dishList.stream().map((item)->{
            DishDto dishdto = new DishDto();
            BeanUtils.copyProperties(item,dishdto);
            Long categoryId = item.getCategoryId();//分类id
            Category category = categoryService.getById(categoryId);
            if(category!=null){
                dishdto.setCategoryName(category.getName());
            }else{
                dishdto.setCategoryName("无");
            }

            //菜品序号
            Long dishId = item.getId();
            LambdaQueryWrapper<DishFlavor> queryWrapper1 = new LambdaQueryWrapper<>();
            queryWrapper1.eq(DishFlavor::getDishId,dishId);
            List<DishFlavor> dishFlavors = dishFlavorService.list(queryWrapper1);
            dishdto.setFlavors(dishFlavors);
            return dishdto;
        }).collect(Collectors.toList());

        //添加redis缓存
        redisTemplate.opsForValue().set(key,dishDtoList,60, TimeUnit.MINUTES);

        return R.success(dishDtoList);
    }

    /**
     * 菜品停售||起售
     * @param status
     * @param ids
     * @return
     */
    @PostMapping("/status/{status}")
    public R<List<Dish>> updateStatus(@PathVariable Integer status,@RequestParam List<Long> ids){
        log.info("Id {}", ids);
        LambdaQueryWrapper<Dish> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.in(Dish::getId,ids);
        List<Dish> dishList = dishService.list(queryWrapper);
        dishList.stream().map((item)->{
            item.setStatus(status);
            return item;
        }).collect(Collectors.toList());

        dishService.updateBatchById(dishList);

        return R.success(dishList);
    }





}
